<template>
	<view @click="sendCode" class="code-btn bg-main" hover-class="bg-main-hover">
		{{ time > 0 ? time + 's' : '发送' }}
	</view>
</template>

<script>
let timer = null;
import initApi from '@/apis/init.js';
export default {
	name: 'code-btn',
	props: {
		phone: {
			type: [Number, String],
			default: ''
		}
	},
	data() {
		return {
			time: 0
		};
	},
	methods: {
		sendCode() {
			console.log('hello', initApi);
			if (this.time > 0) {
				return;
			}
			initApi
				.authSendSms({
					mobile: this.phone
				})
				.then((res) => {
					console.log(res);
					if (res.code == 20000) {
						uni.utils.toast('发送成功');
					} else {
						return uni.utils.toast(res.message);
					}
					this.time = 60;
					timer = setInterval(() => {
						this.time--;
						if (this.time <= 0) {
							clearInterval(timer);
						}
					}, 1000);
				})
				.catch((err) => {
					console.log(err);
				});
		}
	}
};
</script>

<style>
.code-btn {
	position: absolute;
	top: 0;
	right: 0;
	bottom: 0;
	z-index: 99;
	width: 200rpx;
	font-size: 14px;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #ffffff;
	border-top-right-radius: 8rpx;
	border-bottom-right-radius: 8rpx;
}
/* 主背景色 */
.bg-main {
	background-color: rgb(92, 204, 132);
}
</style>
